<?php

class MemberController extends Controller {

	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout = '//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters() {
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules() {
		return array(
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions' => array('old', 'index', 'view', 'excel', 'excelOld', 'edit', 'editMembership', 'mutation'),
				'roles' => array('sektion'),
			),
			array('deny', // deny all users
				'users' => array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id) {
		$model = $this->loadModel($id);
		$attributeChanges = AttributeChange::model()->getOpenChangesByMember($model);
		$membershipChanges = MembershipChange::model()->getOpenChangesByMember($model);
		$this->render('view', array(
			'model' => $model,
			'attributeChanges' => $attributeChanges,
			'membershipChanges' => $membershipChanges,
		));
	}

	/**
	 * List Members.
	 */
	public function actionIndex() {
		$model = new Member('search');
		$model->unsetAttributes();  // clear any default values
		if (isset($_GET['Member']))
			$model->attributes = $_GET['Member'];

		$codes = Code::model()->findAll("Sprache='Deutsch' AND Haupt_Code = 1059");
		
		$this->render('index', array(
			'model' => $model,
			'codes' => $codes,
		));
	}

	/**
	 * List old Members.
	 */
	public function actionOld() {
		$model = new Member('search');
		$model->unsetAttributes();  // clear any default values
		if (isset($_GET['Member']))
			$model->attributes = $_GET['Member'];

		$this->render('old', array(
			'model' => $model,
		));
	}

	public function actionEdit($id) {

		$member = $this->loadModel($id);
		$model = new AttributeChange;
		$model->loadMember($member);
		$attributeChanges = AttributeChange::model()->getOpenChangesByMember($model);
		$membershipChanges = MembershipChange::model()->getOpenChangesByMember($model);
		
		if (!Member::model()->isActive($model->Benutzernummer) || $attributeChanges || $membershipChanges) {
			throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
		}

		if (isset($_POST['AttributeChange'])) {
			$_POST['AttributeChange']['Email_Geschaeft'] = trim($_POST['AttributeChange']['Email_Geschaeft']);

			$model->attributes = $_POST['AttributeChange'];
			if ($model->save()) {
				$this->sendAttributeChangeMail($model, $member);
				$this->redirect(array('view', 'id' => $model->Benutzernummer));
			} else {
				$model->loadMember($member);
			}
		}


		$this->render('edit', array(
			'model' => $model,
		));
	}

	public function actionEditMembership($id) {

		$member = $this->loadModel($id, true);
		$model = new MembershipChange();

		if (!Member::model()->isActive($member->Benutzernummer)) {
			throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
		}


		if (isset($_POST['MembershipChange'])) {

			$model->setAttributes($_POST['MembershipChange']);

			if ($model->save()) {
				$this->sendMembershipChangeMail($model, $member);
				$this->redirect(array('view', 'id' => $member->Benutzernummer));
			}
		}

		$this->render('changeMembership', array(
			'model' => $model, 'member' => $member,
		));
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionMutation($id) {
		$model = $this->loadModel($id);
		$attributeChanges = AttributeChange::model()->getOpenChangesByMember($model);
		$membershipChanges = MembershipChange::model()->getOpenChangesByMember($model);
		
		if ($attributeChanges){
			$changeModel = $this->getChanges($this->loadChangeModel($id), false);
		} else if ($membershipChanges) {
			$changeModel = $this->loadChangeModel($id);
		} else {
			throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
		}

		$this->render('mutation', array(
			'model' => $model,
			'changeModel' => $changeModel,
			'attributeChanges' => $attributeChanges,
			'membershipChanges' => $membershipChanges,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id, $strict = false) {
		$model = Member::model()->with('memberships')->with('profileExtensions')->regionConstraint($strict)->findByPk($id);
		if ($model === null)
			throw new CHttpException(404, 'The requested page does not exist.');
		return $model;
	}

	private function loadChangeModel($id) {
		$model = AttributeChange::model()->find("Benutzernummer = :user AND confirmationDate = '0000-00-00 00:00:00'", array(":user" => $id));
		if ($model === null)
			$model = MembershipChange::model()->find("Benutzernummer = :user AND confirmationDate = '0000-00-00 00:00:00'", array(":user" => $id));

		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model) {
		if (isset($_POST['ajax']) && $_POST['ajax'] === 'member-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

	private function sendAttributeChangeMail($model, $member) {
		$user = User::model()->with('profile')->findByPk(Yii::app()->user->getId());

		$changes = $this->getChanges($model);

		$message = new YiiMailMessage();
		$message->view = 'memberAttributeChange';
		$message->setBody(array('model' => $model, 'member' => $member, 'user' => $user, 'changes' => $changes), 'text/plain');

		$message->addTo(Yii::app()->params['sekiEmail2']);
		$message->addTo(Yii::app()->params['sekiEmail']);
		$message->from = Yii::app()->params['supportEmail'];
		$message->setSubject("Änderung aus Sektionsportal");

		Yii::app()->mail->send($message);
	}

	private function sendMembershipChangeMail($model, $member) {
		$user = User::model()->with('profile')->findByPk(Yii::app()->user->getId());

		$message = new YiiMailMessage();
		$message->view = 'membershipChange';
		$message->setBody(array('model' => $model, 'member' => $member, 'user' => $user), 'text/plain');

		$message->addTo(Yii::app()->params['sekiEmail2']);
		$message->addTo(Yii::app()->params['sekiEmail']);
		$message->from = Yii::app()->params['supportEmail'];
		$message->setSubject("Änderung aus Sektionsportal");

		Yii::app()->mail->send($message);
	}

	private function getChanges($model, $removeKey = true) {
		$changes = $model->getAttributes();
		$changes["sectionChange"] = ($model->sectionChange == 1 ? "Ja" : "Nein");

		foreach ($changes as $key => $val) {

			// Remove emtpy values
			if (!$val) {
				unset($changes[$key]);
			}
		}

		// Cleanup
		unset($changes["id"]);
		unset($changes["Kundennummer"]);
		unset($changes["Benutzernummer"]);
		unset($changes["userId"]);
		unset($changes["creationDate"]);
		unset($changes["confirmationDate"]);
		if ($removeKey) {
			unset($changes["confirmationKey"]);
		}

		return $changes;
	}

}
